<script setup>
import { onMounted, ref, shallowRef } from "vue";
import router from "@/router/index.js";

const props = defineProps({
	path: {
		type: String,
		default: null,
	},
});

const createRouteMap = (routes, parentPath = "") => {
	let routeMap = {};
	routes.forEach((route) => {
		if (route.path !== "") {
			const fullPath = parentPath + route.path;
			routeMap[fullPath] = {
				name: route.name,
				path: fullPath,
				...(route.children ? { children: createRouteMap(route.children, fullPath + "/") } : {}),
			};
		}
	});
	return routeMap;
};

const findRoute = (path, routeMap) => {
	const pathSegments = path.split("/").filter((segment) => segment !== "");
	let currentRouteMap = routeMap;
	const breadcrumbs = [];
	let accumulatedPath = "";
	for (const segment of pathSegments) {
		accumulatedPath += "/" + segment;
		if (currentRouteMap[accumulatedPath]) {
			breadcrumbs.push({
				name: currentRouteMap[accumulatedPath].name,
				path: accumulatedPath,
			});
			currentRouteMap = currentRouteMap[accumulatedPath].children || {};
		} else break;
	}
	return breadcrumbs;
};
const breadcrumbs = ref([]);

onMounted(() => {
	console.log(window.location);
	const defaultRoute = { name: "首页", path: "/" };
	let routeArr = [...findRoute(props.path ?? window.location.pathname, createRouteMap(router.options.routes))].filter((item) => item !== null);
	breadcrumbs.value = routeArr.length > 0 ? routeArr : [defaultRoute];
});
</script>

<template>
	<div class="breadcrumbContent">
		<n-breadcrumb v-if="breadcrumbs.length > 1">
			<n-breadcrumb-item v-for="(item, index) in breadcrumbs" :href="item.path">
				<div class="hover">
					{{ item.name }}
				</div>
			</n-breadcrumb-item>
		</n-breadcrumb>
	</div>
</template>

<style scoped>
.breadcrumbContent {
	margin-bottom: 10px;
}
.hover:hover {
	cursor: pointer;
	color: #e13d36;
}
</style>
